package com.aios.action.signin;

import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.aios.action.AbstractManagementAction;
import com.aios.entity.SwitchPanel;
import com.aios.entity.SystemUser;
import com.aios.entity.unit.UserType;
import com.aios.exception.SessionNotExist;
import com.aios.service.SwitchPanelService;
import com.aios.service.impl.SystemUserServiceImpl;
import com.aios.util.CookieKey;
import com.aios.util.SessionKey;

@Scope("prototype")
public class SignInAction extends AbstractManagementAction implements ServletRequestAware , ServletResponseAware {

	@Autowired private SystemUserServiceImpl systemUserServiceImpl;
	@Autowired	private SwitchPanelService switchPanelService;

	private static final long serialVersionUID = 1L;
	private static final String ADMIN = "admin";
	private static final String AIOS = "aios";

	private SystemUser systemUser;
	private List<SwitchPanel> switchPanelList;
	private String panelId;

	protected String userKey;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public static final int COOKIE_TIME_OUT = 172800; //60*60*24*2;
	public static final String DEFAULT_USER_ID = "-1";
	public static final int DEFAULT_COOKIE_TIME_OUT=-1;
	public static final String SIGNIN_BY_COOKIE="signin_by_cookie";
	
	public String showSigninForm() {
		if((userKey = userKeyCookie()) != null && !userKey.equals(DEFAULT_USER_ID)) {
			return SIGNIN_BY_COOKIE;
			
		} else{
			return SUCCESS;
		}
		
	}

	public String signIn() {
		
		if((userKey = userKeyCookie()) != null && !userKey.equals(DEFAULT_USER_ID)) {
			systemUser = systemUserServiceImpl.findById(userKeyCookie());
		}else{
			validateSignIn();
			if (hasErrors()) {
				return INPUT;
			}
			systemUser = systemUserServiceImpl.signIn(systemUser.getEmail(), systemUser.getUserPassword());
		}
		
		if (systemUser == null) {
			addActionError(getText("user.login.error.authentication"));
			return INPUT;
		}
		
		removeSwitchedUserSessionVariable();
		addSessionUserVariable(systemUser);
		Cookie userKey = createCookie(COOKIE_TIME_OUT);
		response.addCookie(userKey);

		if (systemUser.getUserType().equalsIgnoreCase(UserType.ADMIN.name())) {
			return ADMIN;
		} else if (systemUser.getUserType().equalsIgnoreCase(
				UserType.AIOS.name())) {
			switchPanelList = switchPanelService
					.findByUserId(getSessionUserVariable().getId());

			if (switchPanelList == null || switchPanelList.size() == 0) {
				actionError = getText("switch.error.panel.not.exist");
				return AIOS;
			} else if (switchPanelList.size() == 1) {
				String url = switchPanelList.get(0).getUrl();
				String http = switchPanelList.get(0).getHttpPort();

				if(url == null || url.equals("") || http == null || http.equals("")) {
					panelId = switchPanelList.get(0).getId();
					actionError = getText("switch.panel.configure.error");
					return AIOS;
				}
			} else if (switchPanelList.size() > 1) {
				panelId = switchPanelList.get(0).getId();
				// use when multiple switch panels available for one user.
			}
		}

		return SUCCESS;
	}

	private void validateSignIn() {
		if (systemUser == null) {
			addActionError(getText("user.invalid.access"));
			return;
		}

		if (systemUser.getEmail().isEmpty()) {
			addFieldError("systemUser.email",
					getText("system.user.email.empty"));
		}

		if (systemUser.getUserPassword().isEmpty()) {
			addFieldError("systemUser.userPassword",
					getText("system.user.password.empty"));
		}
	}

	public String signOut() {

		try {
			Cookie userKey = createCookie(DEFAULT_COOKIE_TIME_OUT);
			response.addCookie(userKey);
			
			if (verifySessionUser()) {
				removeSessionVariable(SessionKey.SESSION_USER);
				removeSessionVariable(SessionKey.SWITCHED_USER);
			}
		} catch (SessionNotExist e) {
			e.printStackTrace();
			// logger
		}

		return SUCCESS;
	}
	
	
	protected Cookie createCookie(int maxTime) {
		String userId = DEFAULT_USER_ID;
		if(systemUser != null) {
			userId = systemUser.getId();
		}
		Cookie c = new Cookie(CookieKey.USER_KEY.name(), userId);
		c.setPath("/");
		c.setMaxAge(maxTime);
		 
		return c;
	}
	
	public static String userKeyCookie() {
		HttpServletRequest request = ServletActionContext.getRequest();
		
		if(request != null && request.getCookies() != null) {
			for(Cookie c : request.getCookies()) {
			      if (c.getName().equals(CookieKey.USER_KEY.name())) {
			    	  return c.getValue();
			      }
			}
		}
		
		return null;
	}

	public SystemUser getSystemUser() {
		return systemUser;
	}

	public void setSystemUser(SystemUser systemUser) {
		this.systemUser = systemUser;
	}

	public List<SwitchPanel> getSwitchPanelList() {
		return switchPanelList;
	}

	public void setSwitchPanelList(List<SwitchPanel> switchPanelList) {
		this.switchPanelList = switchPanelList;
	}

	public String getPanelId() {
		return panelId;
	}

	public void setPanelId(String panelId) {
		this.panelId = panelId;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getUserKey() {
		return userKey;
	}

	public void setUserKey(String userKey) {
		this.userKey = userKey;
	}
	
	
}
	
	

